package com.jch.po.server;

import com.jch.po.domain.Msg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端：" + ctx.channel().remoteAddress().toString() + "接入！");
        String msgContent = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date()) + " 接入服务器：" + ctx.channel().localAddress().toString() + "成功。";
        ctx.writeAndFlush(new Msg(ctx.channel().id().toString(), msgContent));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端：" + ctx.channel().remoteAddress().toString() + " 主动断开连接！");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
        System.out.println(dateStr + " 消息类型：" + msg.getClass());
        System.out.println(dateStr + " 消息内容：" + ((Msg) msg).toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常：" + cause.getMessage());
    }
}
